package com.shixianjun.leetcode;

public class _4_寻找两个正序数组的中位数 {

    static public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length == 0 && nums2.length == 0) return 0;
        int length = nums1.length + nums2.length;
        int sum = 0;
        boolean isDouble = (length & 1) == 0;
        int medianIndex = length >> 1;

        int index1 = 0;
        int index2 = 0;

        int count = 0;
        int currValue = 0;

        while (index1 < nums1.length || index2 < nums2.length) {

            if (index1 >= nums1.length) {
                currValue = nums2[index2];
                index2++;
            } else if (index2 >= nums2.length) {
                currValue = nums1[index1];
                index1++;
            } else if (nums1[index1] < nums2[index2]) {
                currValue = nums1[index1];
                index1++;
            } else {
                currValue = nums2[index2];
                index2++;
            }

            if ((isDouble == true && count == medianIndex - 1) || count == medianIndex) {
                sum += currValue;
            }

            count ++;
        }
        if (isDouble) return sum / 2.0;
        return sum;
    }

    /**
     * 1 3 5
     * 2 4 6
     *
     * */

    public static void main(String[] args) {
        int[] num1 = {1, 3};
        int[] num2 = {3, 5, 7};

        double median = findMedianSortedArrays(num1, num2);

        System.out.print(median);
    }
}
